using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Xml;
using System.Diagnostics;

namespace ArabicNLP_Project
{
    public partial class Debugger : Form
    {
        MorphologicalAnalyzer tester;
        MorphologicalWord result;

        string FileText = "";
        string results = "";
        string status;

        public Debugger()
        {
            InitializeComponent();
            DisplayNewTime("Starting System ....");
            try
            {
                tester = new MorphologicalAnalyzer();
            }
            catch (Exception ex) {
                MessageBox.Show("Error in Reading Data Files!");
            }          
            
            displayDuration("Initialiaze System Time...");
            textBox1.Focus();
                      
        }

        private void displayDuration(string p)
        {
            label2.Text = p+" "+TimingUtilities.GetElapsedTime() + " msec";
            status = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            clearResult();
            DisplayNewTime("Starting Word Analyzer ....");
            result = tester.analyze(textBox1.Text);
            // Diplay time
            displayDuration("Word Analyzer Time...");
            ShowResult();
            textBox1.Text = "";
        }

        private void ShowResult()
        {
            // display output
            int page = 0;
            foreach (MorpholologicalStem root in result.possibleRoots)
            {
                if (page == 0)
                {
                    lblWord.Text = result.originalWord;
                    lblType.Text = root.type.ToString();
                    lblPattern.Text = root.pattern;
                    lblPrefix.Text = root.prefix;
                    lblRoot.Text = root.root;
                    lblSuffix.Text = root.suffix;
                }
                else if (page == 1)
                {
                    label3.Text = result.originalWord;
                    label4.Text = root.type.ToString();
                    label7.Text = root.pattern;
                    label5.Text = root.prefix;
                    label6.Text = root.root;
                    label8.Text = root.suffix;
                }
                else if (page == 2)
                {
                    label9.Text = result.originalWord;
                    label10.Text = root.type.ToString();
                    label13.Text = root.pattern;
                    label11.Text = root.prefix;
                    label12.Text = root.root;
                    label14.Text = root.suffix;
                }
                else if (page == 3)
                {
                    label15.Text = result.originalWord;
                    label16.Text = root.type.ToString();
                    label19.Text = root.pattern;
                    label17.Text = root.prefix;
                    label18.Text = root.root;
                    label20.Text = root.suffix;
                }
                page++;
            }
        }

        private void clearResult()
        {
            // initialize
            int page = 0;

            lblWord.Text = "";
            lblType.Text = "";
            lblPattern.Text = "";
            lblPrefix.Text = "";
            lblRoot.Text = "";
            lblSuffix.Text = "";


            label3.Text = "";
            label4.Text = "";
            label7.Text = "";
            label5.Text = "";
            label6.Text = "";
            label8.Text = "";


            label9.Text = "";
            label10.Text = "";
            label13.Text = "";
            label11.Text = "";
            label12.Text = "";
            label14.Text = "";


            label15.Text = "";
            label16.Text = "";
            label19.Text = "";
            label17.Text = "";
            label18.Text = "";
            label20.Text = "";
        }

        private string readCorpus(string p)
        {
            try
            {
                XmlDocument reader = new XmlDocument();
                reader.Load(p);
                string corpusText = "";
                foreach (XmlNode node in reader.SelectNodes(@"/tei.2/text/body/p"))
                {
                    corpusText += node.InnerText + "\r\n";
                }

                return corpusText;
            }
            catch
            {
                return File.ReadAllText(p);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Text = readCorpus(openFileDialog1.FileName);
            }
        }

        private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
        {
                   
        }

        private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
        {
            textBox1.Text = richTextBox1.SelectedText;  
        }

        private void button2_Click(object sender, EventArgs e)
        {
            progressBar1.Visible = true;
            button2.Enabled = false;
            FileText = richTextBox1.Text;
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.RunWorkerAsync();
            
        }

        private void analyzeFile()
        {
            string[] words = FileText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int wordCount = 0;
            foreach (string word in words)
            {
                result = tester.analyze(word);
                results += result.originalWord + "\t\t";
               
                foreach (MorpholologicalStem stem in result.possibleRoots)
                {                    
                    results += stem.root + "\t\t";
                }
                results += "\r\n";
                if (backgroundWorker1.IsBusy)
                    backgroundWorker1.ReportProgress(wordCount++ * 100 / words.Length);
            }    
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            DisplayNewTime("Processing File...");
            analyzeFile();
        }

        private void DisplayNewTime(string p)
        {
            TimingUtilities.startTimer();
            label2.Text = p;
            status = p;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 100;

            button2.Enabled = true;
            // Create an instance of StreamWriter to write text to a file.
            // The using statement also closes the StreamWriter.
            string FileName = @"results.txt";

            using (StreamWriter sw = new StreamWriter(FileName, false, Encoding.UTF8))
            {
                sw.Write(results);
            }
            Process.Start(FileName);

            progressBar1.Visible = false;
            progressBar1.Value = 0;
            displayDuration("Analyze File Time...");
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label2.Text = status + " " + e.ProgressPercentage + "%";
            clearResult();
            ShowResult();
        }

        private void Debugger_Load(object sender, EventArgs e)
        {

        }
    }
}
